﻿/*
* CRM_Contact.cs
*
* 功 能： N/A
* 类 名： CRM_Contact
*
* Ver    变更日期             负责人     变更内容
* ───────────────────────────────────
* V1.0  2015-06-23 18:38:21    黄润伟    
*
* Copyright (c) 2015 www.xhdcrm.com   All rights reserved.
*┌──────────────────────────────────┐
*│　版权所有：黄润伟                      　　　　　　　　　　　　　　│
*└──────────────────────────────────┘
*/

using System;
using System.Data;
using System.Web;
using XHD.Common;
using XHD.Controller;
using System.IO;

namespace XHD.Server
{
    public class CRM_Contact
    {
        public static BLL.CRM_Contact contact = new BLL.CRM_Contact();
        public static Model.CRM_Contact model = new Model.CRM_Contact();

        public HttpContext Context;
        public int emp_id;
        public string emp_name;
        public Model.hr_employee employee;
        public HttpRequest request;
        public string uid;


        public CRM_Contact()
        {
        }

        public CRM_Contact(HttpContext context)
        {
            Context = context;
            request = context.Request;

            var userinfo = new User_info();
            employee = userinfo.GetCurrentEmpInfo(context);

            emp_id = employee.ID;
            emp_name = PageValidate.InputText(employee.name, 50);
            uid = PageValidate.InputText(employee.uid, 50);
        }

        public void save()
        {
            string customerid = request["T_company_val"];

            model.C_customerid = int.Parse(customerid);
            model.C_name = PageValidate.InputText(request["T_contact"], 250);
            model.C_sex = PageValidate.InputText(request["T_sex"], 250);
            model.C_birthday = PageValidate.InputText(request["T_birthday"], 250);
            model.C_department = PageValidate.InputText(request["T_dep"], 250);
            model.C_position = PageValidate.InputText(request["T_position"], 250);

            model.C_tel = PageValidate.InputText(request["T_tel"], 250);
            model.C_mob = PageValidate.InputText(request["T_mobil"], 250);
            model.C_fax = PageValidate.InputText(request["T_fax"], 250);
            model.C_email = PageValidate.InputText(request["T_email"], 250);
            model.C_QQ = PageValidate.InputText(request["T_qq"], 250);
            model.C_add = PageValidate.InputText(request["T_add"], 250);

            model.C_hobby = PageValidate.InputText(request["T_hobby"], 250);
            model.C_remarks = PageValidate.InputText(request["T_remarks"], 250);

            string contact_id = PageValidate.InputText(request["contact_id"], 50);
            if (PageValidate.IsNumber(contact_id))
            {
                DataSet ds = contact.GetList("id=" + int.Parse(contact_id));
                DataRow dr = ds.Tables[0].Rows[0];

                model.id = int.Parse(contact_id);

                contact.Update(model);

                //日志
                var log = new sys_log();

                int UserID = emp_id;
                string UserName = emp_name;
                string IPStreet = request.UserHostAddress;
                string EventTitle = model.C_name;
                
                string EventType = "联系人修改";
                int EventID = model.id;
                string Log_Content = null;

                if (dr["C_customername"].ToString() != request["T_company"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "公司名称", dr["C_customername"], request["T_company"]);

                if (dr["C_name"].ToString() != request["T_contact"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "联系人", dr["C_name"], request["T_contact"]);

                if (dr["C_sex"].ToString() != request["T_sex"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "联系人性别", dr["C_sex"], request["T_sex"]);

                if (dr["C_birthday"].ToString() != request["T_birthday"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "联系人生日", dr["C_birthday"], request["T_birthday"]);

                if (dr["C_department"].ToString() != request["T_dep"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "联系人部门", dr["C_department"], request["T_dep"]);

                if (dr["C_position"].ToString() != request["T_position"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "联系人职位", dr["C_position"], request["T_position"]);

                if (dr["C_tel"].ToString() != request["T_tel"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "联系人电话", dr["C_tel"], request["T_tel"]);

                if (dr["C_mob"].ToString() != request["T_mobil"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "联系人手机", dr["C_mob"], request["T_mobil"]);

                if (dr["C_fax"].ToString() != request["T_fax"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "联系人传真", dr["C_fax"], request["T_fax"]);

                if (dr["C_email"].ToString() != request["T_email"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "联系人邮箱", dr["C_email"], request["T_email"]);

                if (dr["C_QQ"].ToString() != request["T_qq"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "联系人QQ", dr["C_QQ"], request["T_qq"]);

                if (dr["C_add"].ToString() != request["T_add"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "联系人地址", dr["C_add"], request["T_add"]);

                if (dr["C_hobby"].ToString() != request["T_hobby"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "联系人爱好", dr["C_hobby"], request["T_hobby"]);

                if (dr["C_remarks"].ToString() != request["T_remarks"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "备注", dr["C_remarks"], request["T_remarks"]);

                if (!string.IsNullOrEmpty(Log_Content))
                    log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, Log_Content);
            }
            else
            {
                model.isDelete = 0;
                model.C_createId = emp_id;
                model.C_createDate = DateTime.Now;

                contact.Add(model);
            }
        }

        public string grid()
        {
            int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " id ";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = " desc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total;
            string serchtxt = "1=1";


            if (PageValidate.IsNumber(request["customerid"]))
                serchtxt += $" and C_customerid={int.Parse(request["customerid"])}";

            if (!string.IsNullOrEmpty(request["company"]))
                serchtxt += $" and C_customerid in (select id from CRM_Customer where Customer like N'%{ PageValidate.InputText(request["company"], 255)}%')";

            if (!string.IsNullOrEmpty(request["contact"]))
                serchtxt += $" and C_name like N'%{ PageValidate.InputText(request["contact"], 255) }%'";

            if (!string.IsNullOrEmpty(request["tel"]))
                serchtxt += $" and C_mob like N'%{ PageValidate.InputText(request["tel"], 255) }%'";

            if (!string.IsNullOrEmpty(request["qq"]))
                serchtxt += $" and C_QQ like N'%{ PageValidate.InputText(request["qq"], 255) }%'";

            if (!string.IsNullOrEmpty(request["startdate"]))
                serchtxt += $" and C_createDate >= '{ PageValidate.InputText(request["startdate"], 255) }'";

            if (!string.IsNullOrEmpty(request["enddate"]))
            {
                DateTime enddate = DateTime.Parse(request["enddate"]).AddHours(23).AddMinutes(59).AddSeconds(59);
                serchtxt += $" and C_createDate  <= '{ enddate }'";
            }

            if (!string.IsNullOrEmpty(request["startdate_del"]))
                serchtxt += $" and Delete_time >= '{ PageValidate.InputText(request["startdate_del"], 255) }'";

            if (!string.IsNullOrEmpty(request["enddate_del"]))
            {
                DateTime enddate1 = DateTime.Parse(request["enddate_del"]).AddHours(23).AddMinutes(59).AddSeconds(59);
                serchtxt += $" and Delete_time  <= '{ enddate1 }'";
            }
            if (!string.IsNullOrEmpty(request["smstype"]))
            {
                if (PageValidate.IsNumber(request["smsid"]))
                {
                    BLL.CRM_SMS sms = new BLL.CRM_SMS();
                    DataSet dssms = sms.GetList("id = " + request["smsid"]);

                    if (dssms.Tables[0].Rows.Count > 0)
                        serchtxt += $" and id in ({ dssms.Tables[0].Rows[0]["contact_ids"] })";
                }
                else
                {
                    serchtxt += " and 1=2";
                }
            }
            //权限           

            serchtxt += $" and C_customerid in (select id from CRM_Customer where  { DataAuth() })";

            //context.Response.Write(serchtxt);
            DataSet ds = contact.GetList(PageSize, PageIndex, serchtxt, sorttext, out Total);
            string dt = GetGridJSON.DataTableToJSON1(ds.Tables[0], Total);

            return dt;
        }

        public string form(string id)
        {
            string dt;
            if (PageValidate.IsNumber(id))
            {
                DataSet ds = contact.GetList($"id = {int.Parse(id)}");
                dt = DataToJson.DataToJSON(ds);
            }
            else
            {
                dt = "{}";
            }
            return dt;
        }

        public string del()
        {
            int id = int.Parse(PageValidate.InputText(request["id"], 50));
            DataSet ds = contact.GetList($"id = {id}");
            string EventType = "联系人删除";

            bool isdel = contact.Delete(id);
            if (isdel)
            {
                //日志
                int UserID = emp_id;
                string UserName = emp_name;
                string IPStreet = request.UserHostAddress;
                int EventID = id;
                string EventTitle = ds.Tables[0].Rows[0]["C_name"].ToString();

                var log = new sys_log();
                log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID,"电话" + ds.Tables[0].Rows[0]["C_tel"]);

                return "true";
            }
            return "false";
        }

        public int import()
        {
            string filepath = Context.Server.MapPath(@"~/file/contact/contact.xls");

            Excel.Excel excel = new Excel.Excel(filepath, emp_id);
            int i = excel.Import();

            File.Delete(filepath);

            //日志
            int UserID = emp_id;
            string UserName = emp_name;
            string IPStreet = request.UserHostAddress;
            int EventID = emp_id;
            string EventTitle = $"【{emp_name}】导入联系人";

            var log = new sys_log();

            log.Add_log(UserID, UserName, IPStreet, EventTitle, "联系人导入", EventID, null);
            return i;
        }
        private string DataAuth()
        {
            //权限            
            string uid = employee.uid;
            string returntxt = " 1=1";

            if (uid != "admin")
            {
                var dataauth = new GetDataAuth();
                string txt = dataauth.GetDataAuthByid("1", "Sys_view", emp_id);

                string[] arr = txt.Split(':');
                switch (arr[0])
                {
                    case "none":
                        returntxt = " 1=2";
                        break;
                    case "my":
                        returntxt = $" ( privatecustomer='公客' or Employee_id={ arr[1] })";
                        break;
                    case "dep":
                        if (string.IsNullOrEmpty(arr[1]))
                            returntxt = $" ( privatecustomer='公客' or Employee_id={ emp_id })";
                        else
                            returntxt = $" ( privatecustomer='公客' or Department_id={ arr[1] })";
                        break;
                    case "depall":
                        var dep = new BLL.hr_department();
                        DataSet ds = dep.GetAllList();
                        string deptask = GetTasks.GetDepTask(int.Parse(arr[1]), ds.Tables[0]);
                        string intext = arr[1] + "," + deptask;
                        returntxt = $" ( privatecustomer='公客' or Department_id in ({ intext.TrimEnd(',') }))";
                        break;
                }
            }

            return returntxt;
        }
    }
}